package com.test.mina2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinaClient01 {

	private static Logger logger = LoggerFactory.getLogger(MinaClient01.class);
	private static String HOST = "localhost";
	private static Integer PORT = 9999;

	public static void main(String[] args) {
		// 创建一个非阻塞的客户端程序
		IoConnector connector = new NioSocketConnector();
		// 设置链接超时时间
		connector.setConnectTimeout(30);
		// 添加过滤器
		connector.getFilterChain().addLast(
			"myChainFilter",
			new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),
				LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue())));
		// 添加业务逻辑处理器类
		connector.setHandler(new Demo1ClientHandler());
		IoSession session = null;
		ConnectFuture future = null;
		try {
			while (true) {
				if (future == null || !future.isConnected()) {
					future = connector.connect(new InetSocketAddress(HOST, PORT));// 创建连接
					future.awaitUninterruptibly();// 等待连接创建完成
				}
				if (session == null || !session.isConnected() || session.isClosing()) {
					session = future.getSession();// 获得session
				} else {
					InputStreamReader reader = new InputStreamReader(System.in);
					BufferedReader bfReader = new BufferedReader(reader);
					String value = bfReader.readLine();
					session.write(value);// 发送消息
					if ("bye".equalsIgnoreCase(value)) {
						break;
					}
				}
			}
		} catch (Exception e) {
			logger.error("客户端链接异常...", e);
			System.out.println("客户端链接异常..." + e);
		}
		session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
		// 关闭客户端
		connector.dispose();

	}

}
